//
/**
 * Filename: fig10-23_sigsuspend2.c
 * Author:   csbonkers
 * Contact:  forever65535@qq.com
 * Date:     2021/6/19
 * Description:
 *    用 sigsuspend 修改全局变量
 */
#include "apue.h"

volatile sig_atomic_t quitflag;
static void sig_int(int signo) {// one signal handler for SIGINT and SIGQUIT
  switch (signo) {
    case SIGINT:
      printf("\ninterrupt\n");
      break;
    case SIGQUIT:
      quitflag = 1;
      break;
    default:
        /*ignore*/;
  }
}
int main(int argc, char *argv[]) {
  if (c_signal(SIGINT, sig_int) == SIG_ERR) {
    err_sys("signal(SIGINT) error");
  }
  if (c_signal(SIGQUIT, sig_int) == SIG_ERR) {
    err_sys("signal(SIGQUIT error)");
  }
  sigset_t newmask, oldmask, zeromask;
  sigemptyset(&newmask);
  sigaddset(&newmask, SIGQUIT);
  sigemptyset(&zeromask);
  // block SIGQUIT and save current signal mask
  if(sigprocmask(SIG_BLOCK,&newmask, &oldmask) < 0){
    err_sys("SIG_BLOCK error");
  }
  while (quitflag == 0){
    sigsuspend(&zeromask);
  }
  /*
   * SIGQUIT has been caught and is now blocked; do whatever
   */
  quitflag = 0;
  /*
   *  reset signal mask which unblock SIGQUIT
   */
  if(sigprocmask(SIG_SETMASK,&oldmask,NULL) < 0){
    err_sys("SIG_SETMASK error");
  }
  return 0;
}